package switchviz.recording;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import switchviz.core.SwitchVizException;
import switchviz.core.alias.AliasFacade;
import switchviz.core.mib.MIBFacade;
import switchviz.core.signal.ISignal;
import switchviz.core.signal.SignalUtil;
import switchviz.network.NetworkException;
import switchviz.network.netswitch.SwitchDataModel;

public class Record
{
	private static Logger logger = Logger.getLogger(Record.class);
	
	private File _path = null;
	private List<ISignal> _signals = new ArrayList<ISignal>();
	private RecordDataModel _recdm = null;
	
	/* c'tors ****************************************************************/
	public Record(File path)
	{
		_path = path;
	}
	
	public RecordDataModel getRecordDataModel()
	{
		if(_recdm == null)
			_recdm = new RecordDataModel();
		return _recdm;
	}
	
	public void setSwitchDataModel(SwitchDataModel switchdm) throws NetworkException
	{
		getRecordDataModel().setSwitchPortCount(switchdm.getPortList());
	}
	
	public void add(String alias) throws RecordingException
	{
		try
		{
			boolean portRequired = MIBFacade.isPortRequired(AliasFacade.getOid(alias));
			
			if (portRequired)
			{
				for (int i = 0; i < getRecordDataModel().getSwitchPortCount().size(); ++i)
				{
					int port = Integer.valueOf(getRecordDataModel().getSwitchPortCount().get(i));
					ISignal signal = SignalUtil.findSignal(_signals, alias, port);
					
					if (signal == null)
						addSignal(new RecordSignal(_path, alias, port));
				}
			}
			else
			{
				ISignal signal = SignalUtil.findSignal(_signals, alias, 0);
				
				if (signal == null)
					addSignal(new RecordSignal(_path, alias));
			}
		}
		catch (SwitchVizException e)
		{
			throw new RecordingException("Error adding record for alias '" + alias + "'.", e);
		}
	}
	
	public List<ISignal> getSignals()
	{
		return _signals;
	}
	
	public void write()
	{
		for (int i = 0; i < _signals.size(); ++i)
		{
			RecordSignal signal = (RecordSignal)_signals.get(i); 

			signal.write();
		}
	}
	
	public void close() throws IOException
	{
		for (int i = 0; i < _signals.size(); ++i)
		{
			RecordSignal signal = (RecordSignal)_signals.get(i); 
			try
			{
				signal.close();
			}
			catch (SwitchVizException e)
			{
				logger.error("Error closing record for signal '" + signal.getAliasName()
					+ " (port=" + signal.getPort() + ")'.", e);
			}
		}	
		RecordPersistence.getInstance().writeRecordInfo(getRecordDataModel(), _path);
	}
	
	private void addSignal(ISignal signal)
	{
		if (signal != null)
		{
			logger.info("Add signal '" + signal.getAliasName() 
				+ " (port=" + signal.getPort() + ")'.");
			
			_signals.add(signal);
		}
	}
}
